<template>
	<view class="page">
    <u-navbar :fixed="false" title="货位调整" :autoBack="true" bgColor="#F9F9F9"></u-navbar>
    <view class="tabs">
      <u-tabs :activeStyle="{color: '#3c9cff'}" :current="tabsCurrent" :list="tabsList" @change="tabsChange" :scrollable="false"></u-tabs>
    </view>
    <template v-if="tabsCurrent==0">
      <view class="search">
        <view class="form-info u-m-b-32">
          <view class="form-lable" style="width: 120rpx;">仓库</view>
          <view class="form-content" @click="jumpTo('/pages/adjustment/warehouse')">
            <u-input v-model="form.FSrcStockName" readonly placeholder="请选择仓库">
              <template slot="suffix">
              <u-icon name="arrow-right"></u-icon>
              </template>
            </u-input>
          </view>
        </view>
        <template v-if="form.FSrcStockId">
          <view class="form-info u-m-b-32">
            <view class="form-lable">原始货位</view>
            <view class="form-content" @click="jumpTo('/pages/adjustment/position', {FNumber: form.FSrcStockId, type: '1'})">
              <u-input v-model="form.FSrcStockLocName" readonly placeholder="请选择原始货位">
                <template slot="suffix">
                <u-icon name="arrow-right"></u-icon>
                </template>
              </u-input>
            </view>
          </view>
          <view class="form-info u-m-b-32">
            <view class="form-lable">目标货位</view>
            <view class="form-content" @click="jumpTo('/pages/adjustment/position', {FNumber: form.FSrcStockId, type: '2'})">
              <u-input v-model="form.FDestStockLocName" readonly placeholder="请选择目标货位">
                <template slot="suffix">
                <u-icon name="arrow-right"></u-icon>
                </template>
              </u-input>
            </view>
          </view>
        </template>
        <view>
        </view>
      </view>
      <view class="list">
        <u-checkbox-group v-model="selectListId1">
          <u-list pagingEnabled>
            <u-list-item v-for="(item, index) in list1" :key="item.MterialFnumber">
              <view class="list-item">
                <view class="item-title">
                  <u-checkbox :disabled="getDisabledStatus(item.MterialFnumber, 'MterialFnumber')" :name="item.MterialFnumber" />
                  <u-icon name="photo" color="#2979ff" size="28" @click="imageBig(item.MterialFnumber)"></u-icon>
                  <text>{{ item.MterialName }}</text>
                </view>
                <view class="form-info">
                  <view class="form-lable">存货编码</view>
                  <view class="form-content">{{ item.MterialFnumber }}</view>
                </view>
                <view class="u-flex">
                  <view class="u-flex-1 form-info">
                    <view class="form-lable">货位</view>
                    <view class="form-content">{{ item.StockLocName }}</view>
                  </view>
                  <view class="u-flex-1 form-info">
                    <view class="form-lable">货位数量</view>
                    <view class="form-content">{{ item.ExistQty }}</view>
                  </view>
                </view>
                <view class="form-info u-m-b-24">
                  <view class="form-lable">移动数量</view>
                  <view class="form-content">
                    <u-input type="number" border="bottom" @blur="numberBlur1($event, index, item)" v-model="item.number" placeholder="请输入"></u-input>
                  </view>
                  <view class="form-unit" @click="unitClick(item, index, '1')">
                    <text>{{ item.UnitName }}</text><u-icon color="#767a82" size="28rpx" name="arrow-down"></u-icon>
                  </view>
                </view>
                <view class="form-info">
                  <view class="form-lable">目标货位</view>
                  <view class="form-content" @click="jumpTo('/pages/adjustment/position', {FNumber: form.FSrcStockId, type: '3', index})">
                    <u-input border="bottom" v-model="item.FDestStockLocName" readonly placeholder="请选择目标货位">
                      <template slot="suffix">
                        <u-icon name="arrow-right"></u-icon>
                      </template>
                    </u-input>
                  </view>
                </view>
              </view>
            </u-list-item>
          </u-list>
        </u-checkbox-group>
      </view>
      <view class="footer-actions" :class="{pB30: isFullSucreen}">
        <view class="u-flex">
          <view class="u-flex-2 u-p-l-30">
            <u-checkbox-group v-model="isAll1" :disabled="list1.length==0" @change="allCheckboxChange1">
              <u-checkbox
                label="全选"
                name="all"
              >
              </u-checkbox>
            </u-checkbox-group>
          </view>
          <view class="u-flex-1 footer-btn" @click="submit1">确定</view>
        </view>
      </view>
    </template>
    <template v-else-if="tabsCurrent==1">
      <view class="search">
        <view class="form-info u-m-b-32">
          <view class="form-lable" style="width: 120rpx;">仓库</view>
          <view class="form-content" @click="jumpTo('/pages/adjustment/warehouse')">
            <u-input v-model="form.FSrcStockName" readonly placeholder="请选择仓库">
              <template slot="suffix">
              <u-icon name="arrow-right"></u-icon>
              </template>
            </u-input>
          </view>
        </view>
        <template v-if="form.FSrcStockId">
          <view class="form-info u-m-b-32">
            <view class="form-lable u-flex" style="gap: 6rpx;" @click="pickerType = 'type'">
              {{ form.typeName }}
              <u-icon name="arrow-down" size="24rpx"></u-icon>
            </view>
            <view class="form-content">
              <u-input v-model="searchValue" placeholder="请输入">
                <template slot="suffix">
                  <u-button type="primary" size="mini" @click="searchPositionInfo">查询</u-button>
                </template>
              </u-input>
            </view>
          </view>
          <view class="form-info u-m-b-32">
            <view class="form-lable">目标货位</view>
            <view class="form-content" @click="jumpTo('/pages/adjustment/position', {FNumber: form.FSrcStockId, type: '2'})">
              <u-input v-model="form.FDestStockLocName" readonly placeholder="请选择目标货位">
                <template slot="suffix">
                <u-icon name="arrow-right"></u-icon>
                </template>
              </u-input>
            </view>
          </view>
        </template>
        <view>
        </view>
      </view>
      <view class="list">
        <u-checkbox-group v-model="selectListId2">
          <u-list pagingEnabled>
            <u-list-item v-for="(item, index) in list2" :key="index">
              <view class="list-item">
                <view class="item-title">
                  <u-checkbox :disabled="getDisabledStatus(item.StockLocName, 'StockLocName')" :name="item.StockLocName" />
                  <u-icon name="photo" color="#2979ff" size="28" @click="imageBig(item.MterialFnumber)"></u-icon>
                  <text>{{ item.MterialName }}</text>
                </view>
                <view class="form-info">
                  <view class="form-lable">存货编码</view>
                  <view class="form-content">{{ item.MterialFnumber }}</view>
                </view>
                <view class="u-flex">
                  <view class="u-flex-1 form-info">
                    <view class="form-lable">货位</view>
                    <view class="form-content">{{ item.StockLocName }}</view>
                  </view>
                  <view class="u-flex-1 form-info">
                    <view class="form-lable">货位数量</view>
                    <view class="form-content">{{ item.ExistQty }}</view>
                  </view>
                </view>
                <view class="form-info u-m-b-24">
                  <view class="form-lable">移动数量</view>
                  <view class="form-content">
                    <u-input type="number" border="bottom" @blur="numberBlur2($event, index, item)" v-model="item.number" placeholder="请输入"></u-input>
                  </view>
                  <view class="form-unit" @click="unitClick(item, index, '2')">
                    <text>{{ item.UnitName }}</text><u-icon color="#767a82" size="28rpx" name="arrow-down"></u-icon>
                  </view>
                </view>
                <view class="form-info">
                  <view class="form-lable">目标货位</view>
                  <view class="form-content" @click="jumpTo('/pages/adjustment/position', {FNumber: form.FSrcStockId, type: '4', index})">
                    <u-input border="bottom" v-model="item.FDestStockLocName" readonly placeholder="请选择目标货位">
                      <template slot="suffix">
                        <u-icon name="arrow-right"></u-icon>
                      </template>
                    </u-input>
                  </view>
                </view>
              </view>
            </u-list-item>
          </u-list>
        </u-checkbox-group>
      </view>
      <view class="footer-actions" :class="{pB30: isFullSucreen}">
        <view class="u-flex">
          <view class="u-flex-2 u-p-l-30">
            <u-checkbox-group v-model="isAll2" :disabled="list2.length==0" @change="allCheckboxChange2">
              <u-checkbox
                label="全选"
                name="all"
              >
              </u-checkbox>
            </u-checkbox-group>
          </view>
          <view class="u-flex-1 footer-btn" @click="submit2">确定</view>
        </view>
      </view>
    </template>
    <template v-else-if="tabsCurrent==2">
      <view class="total">
        <view class="total-item">总数量 <text>{{ total }}</text></view>
        <view class="total-item">商品种类 <text>{{ FBillEntry.length }}</text></view>
      </view>
      <view class="end-list">
        <u-list>
          <u-list-item v-for="(item, index) in FBillEntry" :key="index">
            <view class="end-item">
              <view class="u-flex u-m-b-18">
                <view class="u-flex-1 h5 u-m-b-0 u-line-1">{{ item.MterialName }}</view>
                <u-icon name="trash" size="42rpx" @click="del(index)"></u-icon>
              </view>
              <view class="form-info">
                <view class="form-lable">存货编码</view>
                <view class="form-content">{{ item.MterialFnumber }}</view>
              </view>
              <view class="u-flex">
                <view class="u-flex-1 form-info">
                  <view class="form-lable">货位</view>
                  <view class="form-content">{{ item.StockLocName }}</view>
                </view>
                <view class="u-flex-1 form-info">
                  <view class="form-lable">货位数量</view>
                  <view class="form-content">{{ item.ExistQty }}</view>
                </view>
              </view>
              <view class="u-flex">
                <view class="u-flex-1 form-info">
                  <view class="form-lable">移动数量</view>
                  <view class="form-content">{{ item.number }}{{ item.UnitName }}</view>
                </view>
                <view class="u-flex-1 form-info">
                  <view class="form-lable">目标货位</view>
                  <view class="form-content">{{ item.FDestStockLocName }}</view>
                </view>
              </view>
            </view>
          </u-list-item>
        </u-list>
      </view>
      <view class="footer-actions" :class="{pB30: isFullSucreen}">
        <view class="u-flex">
          <view class="u-flex-1" />
          <view class="u-flex-1 footer-btn" @click="tabsCurrent=0">继续移货</view>
          <view class="u-flex-1 footer-submit-btn" @click="submit">提交</view>
        </view>
      </view>
    </template>
    <u-picker ref="uPicker" :show="pickerType!=''" :columns="[pickerInfo[pickerType]]" keyName="name" @confirm="pickerConfirm" @cancel="pickerType = ''"></u-picker>
		<u-picker :show="unitShow" :columns="columns" keyName="name" @cancel="unitShow = false" @confirm="confirmUnit"></u-picker>
	</view>
</template>

<script>
import { getPositionInfoByGoodsAnWarehouse, getPositionInfoByStockLocAnWarehouse, getExecuteServiceImg, getBaseImg, getMaterialInformation, dynamicFormServiceSave, adjustmentFormServiceSave, adjustmentFormServiceAudit } from '@/api/index'
import { formatTimeTwo } from '../../common/util.js'

export default {
  data() {
    return {
      isFullSucreen: this.isFullSucreen,
      tabsCurrent: 0,
      tabsList: [
        {
          name: '按货位移',
        },
        {
          name: '按商品移',
        },
        {
          name: '已移库',
        },
      ],
      searchValue: '',
      pickerType: '',
      pickerInfo: {
         type: [
          {
            id: 'materialNumber',
            name: '物料编码'
          },
          {
            id: 'MaterialName',
            name: '物料名称',
          },
          {
            id: 'ModelName',
            name: '规格型号'
          },
        ],
      },
      form: {
        typeName: '物料编码',
        type: 'materialNumber',
        FSrcStockName: '', // 仓库名称
        FSrcStockId: '', // 仓库编码
        FSrcStockLocName: '', // 原始货位名称
        FSrcStockLocId: '', // 原始货位编码
        FDestStockLocName: '', // 目标货位名称
        FDestStockLocId: '', // 目标货位编码
      },
      isAll1: [],
      isAll2: [],
      selectListId1: [],
      selectListId2: [],
      list1: [],
      list2: [],
      orgInfo: {},
      unitIndex: '',
      unitType: '',
      unitShow: false,
      columns: [],
      FBillEntry: [],
    }
  },
  computed: {
    total: function () {
      let sum = 0;
      for (let i = 0; i < this.FBillEntry.length; i++) {
        sum = sum + Number(this.FBillEntry[i].number)
      }
      return sum
    },
  },
  watch: {
    selectListId1(n) {
      if(n.length == this.list1.length) {
        this.isAll1 = ['all']
      } else {
        this.isAll1 = []
      }
    },
    selectListId2(n) {
      if(n.length == this.list2.length) {
        this.isAll2 = ['all']
      } else {
        this.isAll2 = []
      }
    },
    // 仓库
    'form.FSrcStockId'() {
      this.form.FSrcStockLocName = ''
      this.form.FSrcStockLocId = ''
      this.form.FDestStockLocName = ''
      this.form.FDestStockLocId = ''
    },
    // 原始货位
    'form.FSrcStockLocId'(n) {
      if(n && n == this.form.FDestStockLocId) {
        uni.showToast({
          title: '原始货位和目标货位不能是一个',
          icon: 'none',
        })
        this.form.FSrcStockLocName = ''
        this.form.FSrcStockLocId = ''
      }
      this.selectPositionInfo()
    },
    // 目标货位
    'form.FDestStockLocId'(n) {
      if(n && n == this.form.FSrcStockLocId) {
        uni.showToast({
          title: '原始货位和目标货位不能是一个',
          icon: 'none',
        })
        this.form.FDestStockLocName = ''
        this.form.FDestStockLocId = ''
      }
    },
  },
  onLoad() {
    this.orgInfo = uni.getStorageSync('orgInfo')
  },
  onShow() {
  },
  methods: {
    del(index) {
      const that = this
      uni.showModal({
        title: '提示',
        content: '确定删除选中物料',
        success: function (res) {
          if(res.confirm) {
            that.FBillEntry.splice(index, 1)
            uni.showToast({
              title: '删除成功',
              icon: 'none'
            });
          }
        }
      });
    },
    submit1() {
      if(this.selectListId1.length == 0) {
        uni.showToast({
          title: '至少移动一个物料',
          icon: 'none'
        });
        return
      }
      const that = this
      uni.showModal({
        title: '提示',
        content: '确定将选中物料添加至移库列表',
        success: function (res) {
          if(res.confirm) {
            const arr = that.list1.filter(v => {
              const index = that.selectListId1.findIndex(j => j == v.MterialFnumber)
              if(index != -1) {
                return v
              }
            })
            let f1 = arr.some(v => v.number <= 0)
            if(f1) {
              uni.showToast({
                title: '选中的物料未填写正确的移动数量',
                icon: 'none'
              });
              return
            }
            arr.forEach(v => {
              v.FSrcStockName = that.form.FSrcStockName
              v.FSrcStockId = that.form.FSrcStockId
              v.FSrcStockLocName = that.form.FSrcStockLocName
              v.FSrcStockLocId = that.form.FSrcStockLocId
              if(!v.FDestStockLocId) {
                v.FDestStockLocName = that.form.FDestStockLocName
                v.FDestStockLocId = that.form.FDestStockLocId
              }
            })
            let f2 = arr.some(v => v.FDestStockLocId == '')
            if(f2 && !that.form.FDestStockLocId) {
              uni.showToast({
                title: '未选择目标货位',
                icon: 'none'
              });
              return
            }
            that.FBillEntry = arr
            uni.showToast({
              title: '添加成功',
              icon: 'none'
            });
          }
        }
      });
    },
    submit2() {
      if(this.selectListId2.length == 0) {
        uni.showToast({
          title: '至少移动一个物料',
          icon: 'none'
        });
        return
      }
      const that = this
      uni.showModal({
        title: '提示',
        content: '确定将选中物料添加至移库列表',
        success: function (res) {
          if(res.confirm) {
            const arr = that.list2.filter(v => {
              const index = that.selectListId2.findIndex(j => j == v.StockLocName)
              if(index != -1) {
                return v
              }
            })
            console.log(arr);
            let f1 = arr.some(v => v.number <= 0)
            if(f1) {
              uni.showToast({
                title: '选中的物料未填写正确的移动数量',
                icon: 'none'
              });
              return
            }
            arr.forEach(v => {
              v.FSrcStockName = that.form.FSrcStockName
              v.FSrcStockId = that.form.FSrcStockId
              if(!v.FDestStockLocId) {
                v.FDestStockLocName = that.form.FDestStockLocName
                v.FDestStockLocId = that.form.FDestStockLocId
              }
            })
            let f2 = arr.some(v => v.FDestStockLocId == '')
            if(f2 && !that.form.FDestStockLocId) {
              uni.showToast({
                title: '未选择目标货位',
                icon: 'none'
              });
              return
            }
            that.FBillEntry = arr
            uni.showToast({
              title: '添加成功',
              icon: 'none'
            });
          }
        }
      });
    },
    submit() {
      if(this.FBillEntry.length == 0) {
        uni.showToast({
          title: '至少移动一个物料',
          icon: 'none'
        });
        return
      }
      const FBillEntry = []
      this.FBillEntry.forEach(v => {
        const info = {
          "FRowType": "Standard",
          "FMaterialId": {
              "FNumber": v.MterialFnumber
          },
          "FUnitID": {
              "FNumber": v.UnitNumber
          },
          "FQty": v.number,
          "FSrcStockId": {
              "FNumber": v.FSrcStockId
          },
          "FSrcStockLocId": {
              "FNumber": v.FSrcStockLocId,
              "FSRCSTOCKLOCID__FF100002": {
                  "FNumber": v.FSrcStockLocId
              }
          },
          "FDestStockId": {
              "FNumber": v.FSrcStockId
          },
          "FDestStockLocId": {
              "FDESTSTOCKLOCID__FF100002": {
                  "FNumber": v.FDestStockLocId
              }
          },
          "FSrcStockStatusId": {
              "FNumber": "KCZT01_SYS"
          },
          "FDestStockStatusId": {
              "FNumber": "KCZT01_SYS"
          },
          "FBusinessDate": formatTimeTwo(new Date(), 'Y-M-D'),
          "FOwnerTypeOutId": "BD_OwnerOrg",
          "FOwnerOutId": {
              "FNumber": "100"
          },
          "FOwnerTypeId": "BD_OwnerOrg",
          "FOwnerId": {
              "FNumber": this.orgInfo.orgId
          },
          "FBaseUnitId": {
              "FNumber": v.UnitNumber
          },
          "FBaseQty": v.number,
          "FKeeperTypeId": "BD_KeeperOrg",
          "FKeeperId": {
              "FNumber": this.orgInfo.orgId
          },
          "FKeeperTypeOutId": "BD_KeeperOrg",
          "FKeeperOutId": {
              "FNumber": this.orgInfo.orgId
          },
          "FDestMaterialId": {
              "FNUMBER":v.MterialFnumber
          },
          "FSaleUnitId": {
              "FNumber": v.UnitNumber
          },
          "FSaleQty": v.number,
          "FSalBaseQty": v.number,
          "FPriceUnitID": {
              "FNumber": "xiang"
          },
          "FPriceQty": v.number,
          "FPriceBaseQty": v.number,
          "F_PCYE_Qty_83g": v.ExistQty,
          "F_PCYE_Qty_re5": v.ExistQty,
          "F_PCYE_Qty_qtr": v.ExistQty,
          "F_PCYE_Qty_qtr1": v.ExistQty,
          "F_PCYE_Remarks_83g": v.FDestStockLocId,
          "F_PCYE_Remarks_re5": v.FSrcStockLocId
        }
        FBillEntry.push(info)
      })
      const parameters = [
        "STK_TransferDirect",
        {
          "NeedUpDateFields": [],
          "NeedReturnFields": [],
          "IsDeleteEntry": "true",
          "SubSystemId": "",
          "IsVerifyBaseDataField": "false",
          "IsEntryBatchFill": "true",
          "ValidateFlag": "true",
          "NumberSearch": "true",
          "IsAutoAdjustField": "true",
          "InterationFlags": "",
          "IgnoreInterationFlag": "",
          "IsControlPrecision": "false",
          "ValidateRepeatJson": "false",
          "Model": {
              "FID": 0,
              "FBillTypeID": {
                  "FNUMBER": "ZJDB01_SYS"
              },
              "FBizType": "NORMAL",
              "FTransferDirect": "GENERAL",
              "FTransferBizType": "InnerOrgTransfer",
              "FSaleOrgId": {
                  "FNumber": this.orgInfo.orgId
              },
              "FSettleOrgId": {
                  "FNumber": this.orgInfo.orgId
              },
              "FStockOutOrgId": {
                  "FNumber": this.orgInfo.orgId
              },
              "FOwnerTypeOutIdHead": "BD_OwnerOrg",
              "FOwnerOutIdHead": {
                  "FNumber": this.orgInfo.orgId
              },
              "FStockOrgId": {
                  "FNumber": this.orgInfo.orgId
              },
              "FIsPriceExcludeTax": true,
              "FIsIncludedTax": true,
              "FExchangeRate": 1.0,
              "FSETTLECURRID": {
                  "FNUMBER": "PRE001"
              },
              "FOwnerTypeIdHead": "BD_OwnerOrg",
              "FExchangeTypeId": {
                  "FNUMBER": "HLTX01_SYS"
              },
              "FOwnerIdHead": {
                  "FNumber": this.orgInfo.orgId
              },
              "FDate": formatTimeTwo(new Date(), 'Y-M-D'),
              "FCustID": {
                  "FNUMBER": this.orgInfo.orgId
              },
              "FSUPPLIERID": {
                  "FNUMBER": this.orgInfo.orgId
              },
              "F_PCYE_CheckBox_qtr": true,
              "FBillEntry": FBillEntry
          }
        }
      ]
      uni.showLoading({ mask: true });
      dynamicFormServiceSave({parameters}).then(res => {
        if(res.Result.ResponseStatus.IsSuccess) {
          const subReview = [
            'STK_TransferDirect',
            {
              "CreateOrgId": 0,
              "Numbers": res.Result.Number,
              "Ids": "",
              "SelectedPostId": 0,
              "UseOrgId": 0,
              "NetworkCtrl": "",
              "IgnoreInterationFlag": ""
            }
          ]
          adjustmentFormServiceSave({parameters: subReview}).then(subReviewRes => {
            if(subReviewRes.Result.ResponseStatus.IsSuccess) {
              const reviewSuc = [
                'STK_TransferDirect',
                {
                  "CreateOrgId": 0,
                  "Numbers": res.Result.Number,
                  "Ids": "",
                  "InterationFlags": "",
                  "UseOrgId": 0,
                  "NetworkCtrl": "",
                  "IsVerifyProcInst": "true",
                  "IgnoreInterationFlag": "",
                  "UseBatControlTimes": "false"
                }
              ]
              adjustmentFormServiceAudit({parameters: reviewSuc}).then(reviewSucRes => {
                if(reviewSucRes.Result.ResponseStatus.IsSuccess) {
                  uni.showToast({
                    title: '调整成功',
                    icon: "none",
                  });
                  setTimeout(function() {
                    uni.redirectTo({
                      url: '/pages/index/index'
                    });
                  }, 1500)
                } else {
                  uni.showModal({
                    title: '审核失败',
                    content: reviewSucRes.Result.ResponseStatus.Errors[0].Message,
                    showCancel: false,
                    success: function (res) {
                    }
                  });
                }
              })
            } else {
              uni.showModal({
                title: '提交审核失败',
                content: subReviewRes.Result.ResponseStatus.Errors[0].Message,
                showCancel: false,
                success: function (res) {
                }
              });
            }
          })
        } else {
          // uni.showToast({
          //   title: res.Result.ResponseStatus.Errors[0].Message,
          //   icon: 'none'
          // });
          uni.showModal({
            title: '调整失败',
            content: res.Result.ResponseStatus.Errors[0].Message,
            showCancel: false,
            success: function (res) {
            }
          });
        }
      })
    },
    allCheckboxChange1(n) {
      if(n.length) {
        this.selectListId1 = this.list1.map(v => v.MterialFnumber)
      } else {
        this.selectListId1 = []
      }
    },
    allCheckboxChange2(n) {
      if(n.length) {
        this.selectListId2 = this.list2.map(v => v.StockLocName)
      } else {
        this.selectListId2 = []
      }
    },
    getDisabledStatus(n, name) {
      return this.FBillEntry.some(v => v[name] == n)
    },
    numberBlur1(e, index, item) {
      if(Number(e) > Number(item.ExistQty)) {
        uni.showToast({
          title: '移动数量不能大于货位数量',
          icon: 'none'
        });
        item.number = Number(item.ExistQty)
        this.$set(this.list1, index, item)
      }
    },
    numberBlur2(e, index, item) {
      console.log(item);
      if(Number(e) > Number(item.ExistQty)) {
        uni.showToast({
          title: '移动数量不能大于货位数量',
          icon: 'none'
        });
        item.number = Number(item.ExistQty)
        this.$set(this.list2, index, item)
      }
    },
    tabsChange(e) {
      this.tabsCurrent = e.index
    },
    selectPositionInfo() {
      const parameters = {
        stockLocNumber: this.form.FSrcStockLocId,
        stockOrgNumber: this.orgInfo.orgId,
        stockNumber: this.form.FSrcStockId,
      }
      uni.showLoading({ mask: true });
      getPositionInfoByStockLocAnWarehouse({ "parameters": [ parameters ] }).then(res => {
				uni.hideLoading();
        if(res.IsSuccess !== 'false') {
          res.stockList.forEach(v => v.number = 0)
          this.list1 = res.stockList
        }
      })
    },
    searchPositionInfo() {
      const parameters = {
        ModelName: '',
        MaterialName: '',
        materialNumber: '',
        stockOrgNumber: this.orgInfo.orgId,
        stockNumber: this.form.FSrcStockId,
      }
      if(this.form.type == 'materialNumber') {
          parameters.materialNumber = this.searchValue // 000024
        } else if(this.form.type == 'MaterialName') {
          parameters.MaterialName = this.searchValue
        } else {
          parameters.ModelName = this.searchValue
        }
      uni.showLoading({ mask: true });
      getPositionInfoByGoodsAnWarehouse({ "parameters": [ parameters ] }).then(res => {
				uni.hideLoading();
        if(res.IsSuccess !== 'false') {
          res.stockList.forEach(v => v.number = 0)
          this.list2 = res.stockList
        }
      })
    },
    // 获取计价单位
    unitClick(item, index, type) {
      this.unitIndex = index
      this.unitType = type
      this.columns = []
      uni.showLoading({ mask: true });
      const parameters = [
        {
          "FormId": "BD_UNIT",
          "FieldKeys": "fnumber,fname",
          "FilterString": "FUnitGroupId.fname='" + item.UnitName + "'",
          "OrderString": "",
          "TopRowCount": 0,
          "StartRow":0,
          "Limit": 2000,
          "SubSystemId": ""
        }
      ]
      getMaterialInformation({parameters}).then(res => {
        uni.hideLoading();
        let arr = []
        res.forEach(item => {
          let obj = {}
          obj.name = item[1]
          obj.id = item[0]
          arr.push(obj)
        })
        this.columns.push(arr)
        if(this.columns.length == 0) {
          uni.showToast({
            title: '未获取到计价单位',
            icon: 'none'
          });
          return
        }
        this.unitShow = true
      })
    },
    confirmUnit(e) {
      if(this.unitType == '1') {
        this.list1[this.unitIndex].UnitName = e.value[0].name
        this.list1[this.unitIndex].UnitId = e.value[0].id
      } else {
        this.list2[this.unitIndex].UnitName = e.value[0].name
        this.list2[this.unitIndex].UnitId = e.value[0].id
      }
      this.unitShow = false
    },
    pickerConfirm(e) {
      if(e.value[0].id) {
        this.form[this.pickerType] = e.value[0].id
        this.form[this.pickerType+'Name'] = e.value[0].name
      } else {
        this.form[this.pickerType] = ''
        this.form[this.pickerType+'Name'] = ''
      }
      this.pickerType = ''
    },
    imageBig(idCode) {
      uni.showLoading({ mask: true });
      getExecuteServiceImg({ "parameters": [ {"MaterialNumber": idCode, "token": uni.getStorageSync('token')} ]}).then(res => {
        function getQueryParam(url, param) {
          // 构造正则表达式，匹配 ? 或 & 后面跟随的参数名称和其值
          const regex = new RegExp('[?&]' + param + '=([^&#]*)', 'i');
          const result = regex.exec(url);
          return result ? decodeURIComponent(result[1]) : null;
        }
        getBaseImg({ "parameters": [ {"FileId": getQueryParam(res.Url, 'fileId'), "StartIndex": 0 } ]}).then(bres => {
          if(bres.Result.FilePart) {
            uni.hideLoading();
            this.overlayImg = 'data:image/png;base64,' + bres.Result.FilePart
            this.overlayShow = true
          } else {
            uni.showToast({
              title: "暂无图片",
              icon: 'none'
            });
          }
        })
      })
    },
    saveBase64ToPhotoAlbum(base64Data) {
      // 1. 去除Base64头部信息（如："data:image/png;base64,"）
      const base64 = base64Data.replace(/^data:image\/\w+;base64,/, '');
      // 2. 转换为ArrayBuffer
      const arrayBuffer = uni.base64ToArrayBuffer(base64);
      // 3. 生成临时文件路径
      const filePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.png`;
      // 4. 写入文件
      const fs = uni.getFileSystemManager();
      return new Promise((resolve, reject) => {
        fs.writeFile({
        filePath,
        data: arrayBuffer,
        encoding: 'binary',
        success: () => {
          // 5. 保存到相册
          uni.saveImageToPhotosAlbum({
            filePath,
            success: () => resolve('保存成功'),
            fail: (err) => reject('保存失败，请检查权限：' + err.errMsg),
          });
        },
        fail: (err) => reject('文件写入失败：' + err.errMsg),
        });
      });
    },
    async saveBase() {
      try {
        uni.showLoading({ mask: true });
        const base64 = this.overlayImg;
        await this.saveBase64ToPhotoAlbum(base64);
        uni.hideLoading()
        uni.showToast({ title: '保存成功', icon: 'success' });
        console.error("保存图片成功");
      } catch (error) {
        console.error("保存图片失败 error：", error);
        uni.showToast({ title: error, icon: 'none' });
        // 处理权限被拒绝的情况
        if (error.includes('authorize')) {
        uni.openSetting({}); // 引导用户打开权限设置
        }
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.page{
	width: 750rpx;
	min-height: 100vh;
  padding-bottom: 40rpx;
  background: #f2f2f2;
  padding: 0 0 188rpx;
  .tabs {
    background: #FFF;
    padding: 10rpx 0 20rpx;
  }
  .search {
    background: #FFF;
    padding: 0 30rpx 20rpx;
    margin-bottom: 20rpx;
  }
  .list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    .list-item {
      width: 100%;
      padding: 10rpx 30rpx 20rpx;
      background: #FFF;
      .item-title {
        display: flex;
        align-items: center;
        gap: 12rpx;
        margin-bottom: 16rpx;
      }
    }
  }
  .total {
    background: linear-gradient(90deg, #2979ff 0%, #7D9EF8 100%);
    padding: 0 30rpx;
    width: 100%;
    height: 80rpx;
    display: flex;
    align-items: center;
    .total-item {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 16rpx;
      color: #fff;
      font-size: 28rpx;
      text {
        font-size: 32rpx;
      }
    }
  }
  .end-list {
    .end-item {
      padding: 30rpx;
      margin-bottom: 20rpx;
      background: #fff;
    }
  }
  .footer-actions {
    border-top: 2rpx solid #d6d7d9;
    background: #fff;
    position: fixed;
    bottom: 0;
    width: 100%;
    z-index: 99;
    .footer-submit-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      height: 90rpx;
      background: linear-gradient(90deg, rgba(236, 210, 161, 1) 0%, rgba(212, 176, 119, 1) 100%);
    }
    .footer-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #FFF;
      background: linear-gradient(90deg, #2979ff 0%, #7D9EF8 100%);
      height: 90rpx;
    }
  }
}
</style>
